﻿using System;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


    public partial class Login2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["GameID"] = "-1";
            Session["UserName"] = null;
            // Hide password recovery hyperlink.
            PasswordRecoverHyperLink1.Visible = false;
            //If firstime loading page login-errors is zero
            if (!this.IsPostBack)

                ViewState["LoginErrors"] = 0;
        }

        //Authenticate when login button is clicked.
        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {

            // Method call for check user credentials procedure.
            if (Checkuseraccount(Login1.UserName, Login1.Password))
            {
                //If found account Authenticate true.
                e.Authenticated = true;

            }

            else
            {
                //Else no account Authenticate false.
                e.Authenticated = false;

            }
        }

        protected void Login1_LoggedIn(object sender, EventArgs e)
        {
            //If useraccount is admin redirect to GlobalSetting page
            Session["UserName"] = Login1.UserName;

            string strConnection = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;
            SqlConnection sqlConnection = new SqlConnection(strConnection);
            String stringselect = @"SELECT GameID FROM GameUsers WHERE UserName=@UserName";
            SqlCommand commandselect = new SqlCommand(stringselect, sqlConnection);
            commandselect.Parameters.AddWithValue("@UserName", Login1.UserName);
            sqlConnection.Open();
            SqlDataReader reader = commandselect.ExecuteReader();
            String gameID = "-1";

            if (reader.Read())
                gameID = reader.GetInt32(0).ToString();

            Session["GameID"] = gameID;

            sqlConnection.Close();

            if (Login1.UserName == "admin")
            {
                Session["Userfield"] = Login1.UserName;
                Response.Redirect("GlobalSetting.aspx");
               

            }
            else
            {
                Session["Userfield"] = Login1.UserName;
                Response.Redirect("Default.aspx");

            }
        }




        //Login error based on global settings to activate password recovery page.
        protected void Login1_LoginError(object sender, EventArgs e)
        {
            // Increment of error count.
            if (ViewState["LoginErrors"] == null)

                ViewState["LoginErrors"] = 0;

            int ErrorCount = (int)ViewState["LoginErrors"] + 1;

            ViewState["LoginErrors"] = ErrorCount;

            //Search password try from database
            string strConnection = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;
            SqlConnection sqlConnection = new SqlConnection(strConnection);
            String stringselect = "Select MaxPasswordTry from GlobalSetting";
            SqlCommand commandselect = new SqlCommand(stringselect, sqlConnection);
            sqlConnection.Open();
            String strmaxpasswordtry = commandselect.ExecuteScalar().ToString();
            int maxpasswordtry = Convert.ToInt32(strmaxpasswordtry);

            //Search account lock in database
            String findisaccountlockedQuery = "SELECT UserName, IsAccountLocked FROM [User] where UserName = @UserName and IsAccountLocked=@IsAccountLocked ";
            SqlCommand commandselect2 = new SqlCommand(findisaccountlockedQuery, sqlConnection);
            SqlParameter findusernameparameter2 = new SqlParameter("@UserName", SqlDbType.VarChar);
            SqlParameter IsAccountLockedparameter = new SqlParameter("@IsAccountLocked", SqlDbType.Bit);
            findusernameparameter2.Value = Login1.UserName;
            IsAccountLockedparameter.Value = true;
            commandselect2.Parameters.Add(findusernameparameter2);
            commandselect2.Parameters.Add(IsAccountLockedparameter);
            SqlDataReader Dr = commandselect2.ExecuteReader();


            //If account in database is locked, display link to password recovery.    
            if (Dr.HasRows == true)
            {

                // Appear password recovery hyperlink.
                Login1.FailureText = "Account is locked , Please click the link below to recover your account";
                PasswordRecoverHyperLink1.Visible = true;

            }

         // If Login error is maxpasswordtry give one last try message prompt.
            else if (ErrorCount == maxpasswordtry)
            {
                Login1.FailureText = "This is your last try before your account is locked out";
            }

        // If Login error is more than maxpasswordtry , lock useraccount and display link to password recovery page.
            else if (ErrorCount > maxpasswordtry)
            {

                String stringcmd = "Update [User] set IsAccountLocked= '" + true + "' where UserName='" + Login1.UserName + "'";
                SqlCommand command = new SqlCommand(stringcmd, sqlConnection);

                Dr.Close();
                command.ExecuteNonQuery();
                sqlConnection.Close();
                Login1.FailureText = "Your account is locked, Please click the link below to recover your account";
                PasswordRecoverHyperLink1.Visible = true;


            }

            sqlConnection.Close();
        }


        //Check user account method
        private bool Checkuseraccount(string username, string Password)
        {
            //Initialize authenticate value false.
            bool boolReturnValue = false;

            //Setup connection string and SQL Query commands and parameters on "User" table database.
            string strConnection = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;
            SqlConnection sqlConnection = new SqlConnection(strConnection);


            String findusernameQuery = "SELECT UserName FROM [User] where UserName = @UserName ";
            String findisaccountlockedQuery = "SELECT UserName, IsAccountLocked FROM [User] where UserName = @UserName and IsAccountLocked=@IsAccountLocked ";
            String finddatabasepassword = "SELECT Hash FROM [User] where UserName = @UserName ";



            SqlCommand command = new SqlCommand(findusernameQuery, sqlConnection);
            SqlCommand command1 = new SqlCommand(findisaccountlockedQuery, sqlConnection);
            SqlCommand command2 = new SqlCommand(finddatabasepassword, sqlConnection);


            SqlParameter findusernameparameter = new SqlParameter("@UserName", SqlDbType.VarChar);

            SqlParameter findusernameparameter2 = new SqlParameter("@UserName", SqlDbType.VarChar);
            SqlParameter IsAccountLockedparameter = new SqlParameter("@IsAccountLocked", SqlDbType.Bit);

            SqlParameter usernameparameter = new SqlParameter("@UserName", SqlDbType.VarChar);



            findusernameparameter.Value = username;

            findusernameparameter2.Value = username;
            IsAccountLockedparameter.Value = true;

            usernameparameter.Value = username;


            command.Parameters.Add(findusernameparameter);

            command1.Parameters.Add(findusernameparameter2);
            command1.Parameters.Add(IsAccountLockedparameter);

            command2.Parameters.Add(usernameparameter);



            //Call-in a Datareader 
            SqlDataReader Dr;


            //Try and catch error while finding records and perfom checks.
            try
            {

                sqlConnection.Open();

                // Find useraccount name in database
                Dr = command.ExecuteReader();


                //If system has found username  in the database execute next the isaccountlocked check.
                if (Dr.HasRows)
                {
                    Dr.Close();
                    Dr = command1.ExecuteReader();

                    //If a system has found useraccount not locked  in the database execute next the find database password.
                    if (Dr.HasRows == false)
                    {
                        Dr.Close();


                        //Decrypt the databasepassword and pass as string.
                        String databasepassword;
                        databasepassword = SSTCryptographer.Decrypt(command2.ExecuteScalar().ToString(), "SampleKey");

                        //Compare database password with the password entered in textbox.
                        if (databasepassword == Password)
                        {
                            //Check if password expired
                            bool resultexpire = PasswordExpiry.Expireday(username);
                            if (resultexpire == true)
                            {

                                //Update User table database login timestamp and allow login.

                                String stringcmd = "Update [User] set LastLoginDate=@updatelogintime where UserName='" + username + "'";
                                SqlCommand updatelogintime = new SqlCommand(stringcmd, sqlConnection);

                                SqlParameter updateloginparameter = new SqlParameter("@updatelogintime", SqlDbType.DateTime);
                                updateloginparameter.Value = System.DateTime.Now;
                                updatelogintime.Parameters.Add(updateloginparameter);
                                Dr.Close();
                                updatelogintime.ExecuteNonQuery();

                                Session["UserName"] = Login1.UserName;

                                String stringselect = @"SELECT GameID FROM GameUsers WHERE UserName=@UserName";
                                SqlCommand commandselect = new SqlCommand(stringselect, sqlConnection);
                                commandselect.Parameters.AddWithValue("@UserName", Login1.UserName);
                                SqlDataReader reader = commandselect.ExecuteReader();
                                String gameID = "-1";

                                if (reader.Read())
                                    gameID = reader.GetInt32(0).ToString();

                                Session["GameID"] = gameID;

                                sqlConnection.Close();

                                //Display error and direct to change password page.
                                Login1.FailureText = "Your password has expired";
                                FormsAuthentication.SetAuthCookie(username, true);
                                Response.Write("<script language='javascript'>alert('Your password has expired, Please enter your new password.');window.location.href='Change Password.aspx'</script>");



                            }

                            else
                            {

                                //Update User table database login timestamp and allow login.

                                String stringcmd = "Update [User] set LastLoginDate=@updatelogintime where UserName='" + username + "'";
                                SqlCommand updatelogintime = new SqlCommand(stringcmd, sqlConnection);

                                SqlParameter updateloginparameter = new SqlParameter("@updatelogintime", SqlDbType.DateTime);
                                updateloginparameter.Value = System.DateTime.Now;
                                updatelogintime.Parameters.Add(updateloginparameter);
                                Dr.Close();
                                updatelogintime.ExecuteNonQuery();


                                //Return authenticate passed.
                                boolReturnValue = true;

                                return boolReturnValue;

                            }


                        }

                        else
                        {
                            Login1.FailureText = "Password is incorrect, Please try again.";

                        }


                    }


                    else
                    {
                        // Appear password recovery hyperlink.
                        Login1.FailureText = "Account is locked , Please click the link below to recover your account";
                        PasswordRecoverHyperLink1.Visible = true;

                    }

                }
                else
                {
                    // Appear password recovery hyperlink.
                    Login1.FailureText = "Username not found , Please click the link below to recover your account";
                    PasswordRecoverHyperLink1.Visible = true;
                }

                Dr.Close();

            }



            catch (Exception ex)
            {

                string errorMessage;
                errorMessage = ("The following error occured :rn" + ex.ToString());
                throw new Exception(errorMessage);
            }

            finally
            {
                //Close SQL connection
                sqlConnection.Close();

            }

            return boolReturnValue;

        }



    }
